﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebNext.Domain;
using System.Web.Mvc;
using WebNext.Domain.Entities;
using WebNext.UI.Utils;
using WebNext.UI.Properties;
using WebNext.UI.Utils.Validators;

namespace WebNext.UI.Models.Login
{
	public class LoginViewModel : MainViewModel
	{
		public string UserName
		{
			get;
			private set;
		}

		public string Password
		{
			get;
			private set;
		}

		public string CaptchaKey
		{
			get;
			set;
		}

		public string CaptchaValue
		{
			get;
			set;
		}

		public bool IsUserNameValid
		{
			get;
			private set;
		}

		public bool IsPasswordValid
		{
			get;
			private set;
		}

		public bool IsCaptchaValid
		{
			get;
			private set;
		}

		public LoginViewModel(string userName, string password) : base(false)
		{
			this.UserName = userName;
			this.Password = password;
			this.IsUserNameValid = true;
			this.IsPasswordValid = true;
			this.IsCaptchaValid = true;

			this.ViewType = MainViewType.Login;
			
			this.PageTitle = string.Format(Resources.TitleFormat, RuntimeSettings.SitePrefix, Resources.Logging);
		}

		public ValidationResult Validate()
		{
			ValidationResult result = new ValidationResult();

			IValidator userNameValidator = new UserNameValidator(this.UserName);
			ValidationResult userNameValidationResult = userNameValidator.Validate();
			if (!userNameValidationResult.IsValid)
			{
				this.IsUserNameValid = false;
				result.Merge(userNameValidationResult);
			}

			IValidator passwordValidator = new PasswordValidator(this.UserName);
			ValidationResult passwordValidationResult = passwordValidator.Validate();
			if (!passwordValidationResult.IsValid)
			{
				this.IsPasswordValid = false;
				result.Merge(userNameValidationResult);
			}

			IValidator captchaValidator = new CaptchaValidator(this.CaptchaKey, this.CaptchaValue);
			ValidationResult captchaValidationResult = captchaValidator.Validate();
			if (!captchaValidationResult.IsValid)
			{
				result.Merge(captchaValidationResult);
				this.IsCaptchaValid = false;
			}
			return result;
		}
	}
}
